package com.example.httpdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG="TAG";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView(){
        Button btnSendGet=findViewById(R.id.btn_send_get);
        Button btnSendPost=findViewById(R.id.btn_send_post);
        btnSendGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendGetHttp();

            }
        });
        btnSendPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendPost();
            }
        });
    }
    private void sendGetHttp(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    //创建访问的url
                    URL url= new URL("http://apis.juhe.cn/simpleWeather/cityList?key=8cf90bdd00d8ff3b42af97f57977b8ba");
                    //打开链接
                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                    //设置参数
                    //设置连接超时时长
                    connection.setConnectTimeout(10*1000);
                    //设置返回超时时长
                    connection.setReadTimeout(10*1000);
                    //设置访问类型，默认为get类型
                    connection.setRequestMethod("GET");
                    //判断网络是否请求成功
                    if (connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                    //获取返回数据
                    InputStream is=connection.getInputStream();
                    String result=inputStream(is);
                    Log.d(TAG,"请求结果："+result);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private void  sendPost(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    //创建访问的url
                    URL url= new URL("http://apis.juhe.cn/simpleWeather/cityList?");
                    //打开链接
                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                    //设置参数
                    //设置连接超时时长
                    connection.setConnectTimeout(10*1000);
                    //设置返回超时时长
                    connection.setReadTimeout(10*1000);
                    //设置访问类型，默认为get类型
                    connection.setRequestMethod("POST");
                    //post请求不支持缓存
                    connection.setUseCaches(false);
                    //开启参数流
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    //key=8cf90bdd00d8ff3b42af97f57977b8ba
                   // String param="key=8cf90bdd00d8ff3b42af97f57977b8ba";
                    String param="key="+URLEncoder.encode("8cf90bdd00d8ff3b42af97f57977b8ba","UTF-8");
                    OutputStream os=connection.getOutputStream();
                    os.write(param.getBytes());
                    //输出流写入完成后刷新
                    os.flush();
                    //判断网络是否请求成功
                    if (connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                        //获取返回数据
                        InputStream is=connection.getInputStream();
                        String result=inputStream(is);
                       // Log.d(TAG,"POST请求结果："+result);
                       // List<CityModel> list=JsonUtil.parseCityList(result);
                        CityModel[] list=JsonUtil.parseCityListByGson(result);
                        for (CityModel model:list) {
                            Log.d(TAG,"id="+model.getId()+"province="+model.getProvince()+
                                    "city="+model.getCity()+"district="+model.getDistrict());

                        }

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private  String inputStream(InputStream is) throws IOException {
        InputStreamReader inputStreamReader=new InputStreamReader(is);
        BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
        StringBuffer sb=new StringBuffer();
        String str="";
        while (null!=(str=bufferedReader.readLine())){
            sb.append(str);
        }
        return  sb.toString();

    }
}